﻿using System;
using Loong.Domain.Entities;
using Loong.Domain.Entities.Auditing;
using Loong.Domain.Uow;
using Loong.Extensions;
using Loong.Runtime.Session;

namespace Loong.Dapper.Filters.Action
{
    public class ModificationAuditDapperActionFilter : DapperActionFilterBase, IDapperActionFilter
    {
        public ModificationAuditDapperActionFilter(
            ILoongSession loongSession,
            IGuidGenerator guidGenerator,
            ICurrentUnitOfWorkProvider currentUnitOfWorkProvider)
            : base(loongSession, guidGenerator, currentUnitOfWorkProvider)
        { }

        public void ExecuteFilter<TEntity, TPrimaryKey>(TEntity entity) where TEntity : class, IEntity<TPrimaryKey>
        {
            if (entity is IHasModificationTime)
            {
                entity.As<IHasModificationTime>().LastModificationTime = DateTime.Now;
            }

            if (entity is IModificationAudited)
            {
                var record = entity.As<IModificationAudited>();
                long? userId = GetAuditUserId();
                if (userId == null)
                {
                    record.LastModifierUserId = null;
                    return;
                }

                record.LastModifierUserId = userId;
            }
        }
    }
}
